﻿using System;
using System.Collections.Generic;

using System.Text;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.DAL;
using System.Data;
using HZ.Common;

namespace HZ.DrugTrade.BLL
{
    public class BLL_CustomGoods : MarshalByRefObject, IBLL_CustomGoods
    {

        #region IBLL_CustomGoods 成员

        /// <summary>
        /// 新增一条自定产品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddCustomGoods(CustomGoods model)
        {
            try
            {
                //附加业务逻辑
                model.AddTime = DateTime.Now;
                model.AuditStatus = 1; //未审核

                return HZ.Data.DAL_Helper.OperateTableSQL(model, HZ.Data.TableOperator.Insert);
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                log4netManager.LogDebug("IBLL_CustomGoods", "出现SqlException", ee);
                return 2;
            };
        }
        /// <summary>
        /// 更新自定义产品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCustomGoods(CustomGoods model)
        {
            try
            {
                //return HZ.Data.DAL_Helper.OperateTableSQL(model, HZ.Data.TableOperator.Update);
                return HZ.Data.DAL_Helper.UpdateModel<Model.CustomGoods>(model);
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                log4netManager.LogDebug("IBLL_CustomGoods", "出现SqlException", ee);
                return 2;
            };

        }
        /// <summary>
        /// 批量更新自定义产品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCustomGoods(List<CustomGoods> model)
        {
            try
            {
                int i = 0;
                foreach (CustomGoods cust in model)
                {
                    i += HZ.Data.DAL_Helper.OperateTableSQL(cust, HZ.Data.TableOperator.Update);
                }
                return i;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                log4netManager.LogDebug("IBLL_CustomGoods", "出现SqlException", ee);
                return 2;
            };

        }
        /// <summary>
        /// 删除自定义产品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int DeleteCustomGoods(CustomGoods model)
        {
            try
            {
                return HZ.Data.DAL_Helper.OperateTableSQL(model, HZ.Data.TableOperator.Delete);
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                log4netManager.LogDebug("IBLL_CustomGoods", "出现SqlException", ee);
                return 2;
            };
        }
        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="customGoodsId"></param>
        /// <returns></returns>
        public CustomGoods GetCustomGoodsByID(string customGoodsId)
        {
            if (HZ.Fun2.IsInt(customGoodsId))
            {
                CustomGoods model = new CustomGoods();
                model.ID = new ConvertHelper(customGoodsId).ToInt32;

                return HZ.Data.DAL_Helper.GetModelByID<CustomGoods>(model);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 分页查询自行添加产品
        /// </summary>
        /// <param name="model"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<HZ.DrugTrade.Model.View.CustomGoods> GetCustomGoodsByWhere(HZ.DrugTrade.Model.Query.CustomGoods model, int currentPage, int pageSize, out int totalRecord)
        {
            string wherestr = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition(model,true);
            string sql = string.Format("SELECT a.*,case AuditStatusMS when 1 then '未审核' when 2 then '需修改' when 3 then '已通过' when 4 then '已拒绝' end as asbyms FROM View_CustomGoods a WHERE 1=1 {0}", wherestr);
            HZ.Data.PageDescribe pdes = new HZ.Data.PageDescribe(sql, pageSize) { CurrentPage = currentPage };
            DataTable dt = pdes.GetSpecailPage();
            totalRecord = pdes.TotalCount;
            return HZ.Data.DAL_Helper.CommonFillList<HZ.DrugTrade.Model.View.CustomGoods>(dt);
        }
        /// <summary>
        /// 分页获取某医疗机构提交的产品信息
        /// </summary>
        /// <param name="hospitalID"></param>
        /// <returns></returns>
        public IList<CustomGoods> GetCustomGoodsByHospital(string hospitalID, int currentPage, int pageSize, out int totalRecord)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 分页获取所有已审核的产品列表（包括审核通过和拒绝通过的）
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<CustomGoods> GetAuditCustomGoods(int currentPage, int pageSize, out int totalRecord)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 分页获取所有待审核的产品列表
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecord"></param>
        /// <returns></returns>
        public IList<CustomGoods> GetUnAuditCustomGoods(int currentPage, int pageSize, out int totalRecord)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取剂型ID add by zdc 升级系统后
        /// </summary>
        /// <param name="medicineModelName"></param>
        /// <returns></returns>
        public string getMedicineModelID(string medicineModelName)
        {
            string medicineModelID = string.Empty;
            var sh = HZ.Data.DbHelperFactory.Create();
            string sql = "SELECT  MedicineModelID FROM TB_MedicineModel WHERE rownum <=1 and MedicineModelName='" + medicineModelName + "'";
            object objMedicineModelID = sh.ExecuteScalar(sql);

            if (objMedicineModelID != null)
            {
                //使用已有剂型
                medicineModelID = objMedicineModelID.ToString();
            }
            return medicineModelID;
        }
        /// <summary>
        /// 获取生产企业ID add by zdc 系统升级后
        /// </summary>
        /// <param name="companyname"></param>
        /// <returns></returns>
        public string Getcompanyid_SC(string companyname)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            string companyID_SC = string.Empty;
            string sql = "SELECT CompanyId FROM TB_Company WHERE  rownum<=1 and  CompanyType='0' AND CompanyName='" + companyname + "'";
            object objCompanyID = sh.ExecuteScalar(sql);

            if (objCompanyID != null)
            {
                //使用已有生产企业
                companyID_SC = objCompanyID.ToString();
            }
            return companyID_SC;
        }
        /// <summary>
        /// 审核自定产品 并添加产品到产品库
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AuditCustomGoods(CustomGoods model, out string goodsID)
        {
            //定义中间数据 ID
            string companyID_SC;

            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                string sql = "";

                # region 生产企业

                sql = "SELECT CompanyId FROM TB_Company WHERE  rownum<=1 and  CompanyType='0' AND CompanyName='" + model.CompanyName + "'";
                object objCompanyID = sh.ExecuteScalar(sql);

                if (objCompanyID != null)
                {
                    //使用已有生产企业
                    companyID_SC = objCompanyID.ToString();
                }
                else
                {
                    //计算出新插入生产企业的ID
                    sql = "SELECT MAX(CompanyId) FROM TB_Company where CompanyId LIKE 'P%' ";
                    objCompanyID = sh.ExecuteScalar(sql);
                    if (objCompanyID != null)
                    {
                        companyID_SC = "P" + (int.Parse(objCompanyID.ToString().Substring(1)) + 1).ToString("D4");
                    }
                    else
                    {
                        companyID_SC = "P0001";
                    }
                    //插入新的生产企业
                    sql = string.Format("INSERT INTO TB_Company ( CompanyID,CompanyName,CompanyType) VALUES( '{0}','{1}','{2}')", companyID_SC, model.CompanyName.Replace("'", ""), "0");
                    //Company companyModel = new Company() { CompanyID = companyID_SC, CompanyName = model.CompanyName };
                    //sql = HZ.Data.DAL_Helper.GetInsertSql(companyModel);
                    sh.ExecuteNonQuery(sql);
                }

                #endregion

                # region 产品信息
                //防止备案采购的流水号和以后的中标流水号重复
                sql = "SELECT MAX(GoodsID) FROM TB_Goods where length(GoodsID)=13";
                object objGoodsID = sh.ExecuteScalar(sql);
                if (objGoodsID != null && objGoodsID.ToString().Length==8)
                {
                    goodsID = (int.Parse(objGoodsID.ToString()) + 1).ToString("D8");
                }
                else
                {
                    goodsID = "1000000000001";
                }

                Goods goodsModel = new Goods()
                {
                    GoodsID = goodsID,
                    //ProductID = productID,
                    Material = model.Material,
                    SortID = model.SortID,
                    QualityLevel = model.QualityLevel,
                    ShortName = model.ShortName,
                    GoodsName = model.GoodsName,
                    Outlookc = model.Outlookc,
                    Unit = model.Unit,
                    PackUnit = model.PackUnit,
                    PinyinCode = HZ.Common.zhHansUtil.GetSpellHeads(model.ShortName),
                    CompanyID_SC = companyID_SC,
                    CompanyName_SC = model.CompanyName,
                    Source = model.Source, //备案产品或未采购产品
                    LimitPrice = model.LimitPrice

                };

                //插入商品信息
                //sql = HZ.Data.DAL_Helper.GetInsertSql(goodsModel);
                //sh.ExecuteNonQuery(sql);
               // HZ.Data.DAL_Helper.InsertModel<Model.Goods>(goodsModel);
                HZ.Data.DAL_Helper.OperateTableSQL<Model.Goods>(goodsModel, HZ.Data.TableOperator.Insert, sh);
                sql = string.Format("update TB_CustomGoods set GoodsId='{0}' where ID='{1}' ", goodsID, model.ID);

                sh.ExecuteNonQuery(sql);

                #endregion


                //更新提交产品的状态
                //sql = HZ.Data.DAL_Helper.GetUpdateSql(model);
                //sh.ExecuteNonQuery(sql);
                //HZ.Data.DAL_Helper.UpdateModel<Model.CustomGoods>(model);
                HZ.Data.DAL_Helper.OperateTableSQL<Model.CustomGoods>(model, HZ.Data.TableOperator.Update, sh);
                sh.CommitTrans();
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_CustomGoods", "出现SqlException", ex);
                goodsID = null;
                return 2;
            }



        }

        #endregion


        /// <summary>
        /// 盟市审核备案产品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AuditCustomGoods(CustomGoods model)
        {
            var sh = HZ.Data.DbHelperFactory.Create();
            try
            {
                sh.BeginTrans(); //锁定表

                #region 盟市审核备案产品

                string sql = string.Format(@"UPDATE TB_CustomGoods 
   SET  AuditStatusMS  = {0}, AuditorMS  = '{1}',AuditNoteMS='{3}',AuditTimeMS=to_date('{4}' , 'yyyy-mm-dd hh24:mi:ss') 
 WHERE ID={2} ", model.AuditStatusMS, model.AuditorMS, model.ID, model.AuditNoteMS, model.AuditTimeMS);
                
                sh.ExecuteScalar(sql);

                #endregion

                sh.CommitTrans();
                return 1;
            }
            catch (Exception ex)
            {
                sh.RollTrans();
                log4netManager.LogDebug("BLL_CustomGoods", "出现SqlException", ex);
                return 2;
            }
        }

    }
}
